package snsdbook.servlets;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import util.SQLUtil;

/**
 * Servlet implementation class PostSubmitServlet
 */
public class PostSubmitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PostSubmitServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  String type = null;
	  String link_url = null;
	  String video_url_parsed = null;
	  String video_url = null;
	  String description = null;
	  String title = null;
	  String tag = null;
	  String image_name = null;
	  InputStream image_content = null;
    String username = (String)request.getSession().getAttribute("username");
	  try {
	    @SuppressWarnings("unchecked")
      List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
      for (FileItem item : items) {
        if (item.isFormField()) {
          String fieldname = item.getFieldName();
          String fieldvalue = item.getString();
          if (fieldname.equals("type")) {
            type = fieldvalue;
          } else if (fieldname.equals("link_url")) {
            link_url = fieldvalue;
          } else if (fieldname.equals("video_url_parsed")) {
            video_url_parsed = fieldvalue;
          } else if (fieldname.equals("video_url")) {
            video_url = fieldvalue;
          } else if (fieldname.equals("description")) {
            description = fieldvalue;
          } else if (fieldname.equals("tag")) {
            tag = fieldvalue;
          } else if (fieldname.equals("title")) {
            title = fieldvalue;
          }
        } else {
          String filename = FilenameUtils.getName(item.getName());
          InputStream filecontent = item.getInputStream();
          image_name = filename;
          image_content = filecontent;
        }
      }
    } catch (Exception e) {
      throw new ServletException("Cannot parse multipart request.", e);
    }
	  
	  String errors = "";
	  
	  if (type.equals("link")) {
	    // URL validation
	    if (description.equals("")) {
	      errors += "Description cannot be empty<br/>";
	    }
	    try {
        URL url = new URL(link_url);
        URLConnection conn = url.openConnection();
        conn.connect();
      } catch (MalformedURLException e) {
        errors += "URL malformed<br/>";
      } catch (IOException e) {
        errors += "URL cannot be reached<br/>";
      }
	  } else if (type.equals("image")) {
	    if (!image_name.endsWith(".jpg") && !image_name.endsWith(".jpeg") &&
	        !image_name.endsWith(".JPG") && !image_name.endsWith(".JPEG")) {
	      errors += "Image must be either JPG or JPEG<br/>";
	    }
	  } else if (type.equals("video")) {
	    if (video_url_parsed.equals("NO")) {
	      errors += "Youtube Link is wrong<br/>";
	    } else {
  	    try {
          URL url = new URL(video_url);
          URLConnection conn = url.openConnection();
          conn.connect();
        } catch (MalformedURLException e) {
          errors += "Youtube Link is wrong<br/>";
        } catch (IOException e) {
          errors += "Youtube Link doesn't exist!<br/>";
        }
	    }
	    
	    if (video_url_parsed.equals("")) {
	      errors += "Unknown Video Error :(\n";
	    }
	  }
	  
	  if (title.equals("")) {
	    errors += "Title must not be empty!<br/>";
	  }
	  
	  if (tag.equals("")) {
	    errors += "Tag must not be empty!<br/>";
	  }
	  
	  if (errors.equals("")) {
	    // OK
	    String text = "";
	    if (type.equals("link")) {
	      text = "<ul>";
	      text += "<li>";
	      text += "<a href='" + link_url + "'>" + link_url + "</a>";
	      text += "</li>";
	      text += "<li>";
	      text += description;
	      text += "</li>";
	      text += "</ul>";
	    } else if (type.equals("image")) {
	      // Writing to disk
	      String putname = String.valueOf(System.currentTimeMillis()) + image_name;
	      System.out.println("Writing " + putname + " to disk...");
	      String path = getServletContext().getRealPath("/resources/images");
	      IOUtils.copy(image_content, new FileOutputStream(new File(path + "/" + putname)));
        
        text = "<img src='/snsdbook/resources/images/" + putname + "'></img>";
	    } else if (type.equals("video")) {
	      text = "<iframe class='youtube-player' type='text/html' width='640' height='385' src='" +
            "http://www.youtube.com/embed/" + video_url_parsed + "' frameborder='0'></iframe>";
	    }
	    
	    // Processing Tag
	    String[] ret = SQLUtil.Query(
	        "SELECT * FROM tag WHERE nama_tag = '" + tag + "'");
	    if (ret.length == 0) {
	      // No such tag, so insert a new one.
	      SQLUtil.Modify("INSERT INTO tag(nama_tag, tag_seo, count) " +
	                     "VALUES('" + tag + "', '" + tag.toLowerCase() +
	                     "', '" + String.valueOf(0) + "')");
	    }
	    
	    String id_tag = SQLUtil.Query(
	        "SELECT id_tag FROM tag WHERE nama_tag = '" + tag + "'")[0];
	    
	    // Write to SQL
      SQLUtil.Modify("INSERT INTO berita(username, judul, judul_seo, isi_berita, " +
                     " waktu, id_tag, gambar, video, dibaca, headline) " +
                     "VALUES('" + username + "', '" +
                                  title + "', '" +
                                  title + "', \"" +
                                  text + "\", '" +
                                  String.valueOf(System.currentTimeMillis()) +
                                  "', '" + id_tag +
                                  "', '" + "" + 
                                  "', '" + "" + 
                                  "', '" + "0" + 
                                  "', '" + "Y" + "')");
      
      response.sendRedirect("ContentList");
	  } else {
	    // Retry
	    request.setAttribute("errors", errors);
	    request.setAttribute("title", title);
      request.setAttribute("description", description);
      request.setAttribute("video_url", video_url);
      request.setAttribute("video_url_parsed", video_url_parsed);
      request.setAttribute("link_url", link_url);
      request.setAttribute("tag", tag);
      RequestDispatcher view = request.getRequestDispatcher("/Post.jsp");
      view.forward(request, response);
	  }
	}

}
